package com.redshark.wmm;

import java.io.IOException;
import java.io.OutputStream;

import android.util.Log;

import com.redshark.wmm.Bluetooth.Bluetooth;


public class BluetoothSender implements Runnable {

	Bluetooth bluetooth;
	OutputStream outputStream;
	
	private static int messageNumCounter;
	private int messageNum;
	private int commandType;
	private int optionalConfig;

	public BluetoothSender(int cmdType, Bluetooth bluetooth) {
		this(cmdType, 0, bluetooth);
	}
	public BluetoothSender(int cmdType, int optionalCnfg, Bluetooth bluetooth) {
		this.messageNum = getMessageNum();
		this.bluetooth = bluetooth;
		this.outputStream = bluetooth.getOutputStream();
		this.commandType = cmdType;
		this.optionalConfig = optionalCnfg;
	}


	@Override
	public void run() {
		sendRequest(commandType);
	}
	
	private static synchronized int getMessageNum(){
		messageNumCounter = (messageNumCounter + 1) % 8;
		return messageNumCounter;
	}

	public void sendRequest(int command) {
		byte[] request = new byte[5];
		if(optionalConfig > 32){ //Check if optional is too big
			optionalConfig = 0;
		}
		
		request[0] = '[';
		request[1] = (byte) (command & 0x7F);
		request[2] = (byte) ((messageNum << 5) | optionalConfig);
		request[3] = (byte) (request[1] ^ request[2]);
		request[4] = ']';
		try {
			outputStream.write(request);
			Log.v("BluetoothSender", "Sent message " + messageNum + " OptCfg: " + optionalConfig);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
